<?php
/**
 * Created by PhpStorm.
 * User: chenxuyi
 * Date: 2018/3/3
 * Time: 上午11:31
 */

namespace App\Validators;

use App\Exceptions\ApiException;
use App\Exceptions\ErrorCode;
use Request;
use Validator;

class BaseValidator
{

    private static $obj = null;

    protected $rules      = [];
    protected $attributes = [];
    protected $message    = [];

    /**
     * validate
     *
     * @param string $key
     *
     * @author chenxuyi
     * @return bool
     * @throws ApiException
     */
    public static function validate(string $key)
    {
        $obj    = self::initial();
        $rules  = $obj->rules[$key];
        $params = Request::all();

        $validator = Validator::make(
            array_only($params, array_keys($rules)),
            $rules,
            $obj->message,
            $obj->attributes
        );

        if (!$validator->passes()) {
            throw new ApiException($validator->errors()->first(), ErrorCode::PARAM_ERROR);
        }

        return true;
    }

    /**
     * initial
     *
     * @author chenxuyi
     * @return null|static
     */
    private static function initial()
    {
        if (!self::$obj instanceof static) {
            self::$obj = new static();
        }

        return self::$obj;
    }

}